package com.fitso.model.dao.hibernate;

import static org.hibernate.criterion.DetachedCriteria.forClass;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Repository;

import com.fitso.model.bean.User;
import com.fitso.model.dao.UserDao;
import com.fitso.model.exception.DuplicateUserException;

@Repository("HibernateUserDao")
public class HibernateUserDao extends HibernateBaseDao implements UserDao {
	public List<User> read() {
		return toList(t().loadAll(User.class), User.class);
	}

	public void createOrUpdate(User user) {
		try {
			t().saveOrUpdate(user);
		}
		catch (DataIntegrityViolationException e) {
			throw new DuplicateUserException(e);
		}
	}

	public User readById(Long id) {
		DetachedCriteria criteria = forClass(User.class);
		criteria.add(Property.forName("id").eq(id));

		return firstItem(t().findByCriteria(criteria), User.class);
	}

	public User readByEmail(String email) {
		DetachedCriteria criteria = forClass(User.class);
		criteria.add(Property.forName("email").eq(email));

		return firstItem(t().findByCriteria(criteria), User.class);
	}

	public void delete(User user) {
		getTemplate().delete(user);
	}
}
